﻿using MaterialSkin.Controls;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Station_interface
{
    public partial class SetdataForm : MaterialForm
    {
        Station_Interface _this;
        public SetdataForm(Station_Interface _buf)
        {
            _this = _buf;
            InitializeComponent();
            //SetStyle(ControlStyles.ResizeRedraw | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true);
            //UpdateStyles();

            DataTable buf = Deserialize<DataTable>(Application.StartupPath + "\\Config\\" + _this.Station_name + "_Info.config");
            if (buf != null)
            {
                GridviewShowDataTable(buf, info_editing_Bas1);
            }

            //禁止用户排序
            if (info_editing_Bas1.Columns.Count > 0)
            {
                for (int i = 0; i < info_editing_Bas1.Columns.Count; i++)
                {
                    info_editing_Bas1.Columns[i].SortMode = DataGridViewColumnSortMode.Programmatic;
                }
            }

            this.Text = "SetdataForm_ " + _this.Station_name;
        }

        private void SetdataForm_Load(object sender, EventArgs e)
        {

        }

        private void SetdataForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            //自动生产报警代码
            AutomaticSorting();

            DataTable buf = GetDataGridView(info_editing_Bas1);
            if (buf != null)
            {
                //Serialize(buf, Application.StartupPath + "\\Config\\" + _this.Station._PlcName + "_Info.config");
            }


            this.Dispose();
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }

        private void info_editing_Bas1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            //判断IP是否符合要求
            string str = info_editing_Bas1.Rows[e.RowIndex].Cells[1].FormattedValue?.ToString();
            if (str == "1" || str == "0")
            {
                info_editing_Bas1.Rows[e.RowIndex].Cells[1].Value = str;
            }
            else
            {
                info_editing_Bas1.Rows[e.RowIndex].Cells[1].Value = str_buf;
                str_buf = "";
            }

            string str2 = info_editing_Bas1.Rows[e.RowIndex].Cells[0].FormattedValue?.ToString();
            if (IsAdd(str2))
            {
                info_editing_Bas1.Rows[e.RowIndex].Cells[0].Value = str2;
            }
            else
            {
                info_editing_Bas1.Rows[e.RowIndex].Cells[0].Value = str_buf;
                str_buf = "";
            }


            //自动生产报警代码
            AutomaticSorting();
        }
        string str_buf = "";
        //编辑中事件
        private void info_editing_Bas1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            DataGridViewTextBoxEditingControl editingControl = e.Control as DataGridViewTextBoxEditingControl;
            str_buf = editingControl.Text;
        }
        //自动生产报警代码
        public void AutomaticSorting()
        {
            for (int i = 0; i < info_editing_Bas1.Rows.Count; i++)
            {
                info_editing_Bas1.Rows[i].Cells[2].Value = i.ToString().PadLeft(4, '0');
            }
        }

        //判断地址是否匹配
        public static bool IsAdd(string s)
        {
            string text1 = @"M\d{0,9000}\.\d{1}$";
            return Regex.IsMatch(s, text1);
        }

        /**********************************************************************************************/
        public int Serialize<T>(T source, string file_path)//序列化方法  
        {
            if (!typeof(T).IsSerializable)
            {
                //MessageBox.Show("类型必须是可序列化", "提示");
                return 1;
            }

            if (Object.ReferenceEquals(source, null))
            {
                //MessageBox.Show("实例不是相同的实例", "提示");
                return 2;
            }
            try
            {
                using (FileStream fs = new FileStream(file_path, FileMode.Create))//创建一个文件流，对文件进行写入
                {
                    BinaryFormatter bf = new BinaryFormatter();//使用CLR二进制格式器
                    bf.Serialize(fs, source); //序列化到硬盘
                    fs.Close();//关闭文件流
                }
                return 0;
            }
            catch
            {
                return 3;
            }
        }
        public T Deserialize<T>(string file_path)
        {
            try
            {
                using (FileStream fs = new FileStream(file_path, FileMode.Open))
                {
                    BinaryFormatter binaryFormatter = new BinaryFormatter();
                    return (T)binaryFormatter.Deserialize(fs);
                }
            }
            catch
            {
                return default(T);
            }
        }

        /// <summary>
        /// DataTable表数据显示到DataGridview 必须要有列名并与DataTable对齐
        /// </summary>
        /// <param name="table">DataTable</param>
        /// <param name="dataGridView">DataGridView</param>
        /// <returns>true成功；false失败</returns>
        public int GridviewShowDataTable(DataTable table, DataGridView dataGridView)
        {
            try
            {
                if (table.Rows.Count > 0)
                {
                    for (int i = 0; i < table.Rows.Count; i++)
                    {
                        dataGridView.Rows.Add();
                        for (int j = 0; j < (table.Columns.Count); j++)
                        {
                            dataGridView.Rows[i].Cells[j].Value = table.Rows[i].ItemArray[j].ToString();
                            //Application.DoEvents();//可以交出控制权但是慢
                        }
                    }
                }

                return 0;
            }
            catch (Exception ex)
            { return 1; }

        }

        /// <summary>
        /// DataGridView导出为Datatable
        /// </summary>
        /// <param name="dgv">DataGridView</param>
        /// <returns>Datatable</returns>
        public DataTable GetDataGridView(DataGridView dgv)
        {
            DataTable dt = new DataTable();

            // 列强制转换
            for (int count = 0; count < dgv.Columns.Count; count++)
            {
                DataColumn dc = new DataColumn(dgv.Columns[count].HeaderText.ToString());
                dt.Columns.Add(dc);
            }

            // 循环行
            for (int count = 0; count < dgv.Rows.Count; count++)
            {
                DataRow dr = dt.NewRow();
                for (int countsub = 0; countsub < dgv.Columns.Count; countsub++)
                {
                    dr[countsub] = Convert.ToString(dgv.Rows[count].Cells[countsub].FormattedValue);
                }
                dt.Rows.Add(dr);
            }
            return dt;
        }


    }
}
